package com.wut.clock.service.impl;

import com.wut.clock.common.constant.MessageConstant;
import com.wut.clock.entity.Message;
import com.wut.clock.entity.SysUser;
import com.wut.clock.event.EventProducer;
import com.wut.clock.mapper.SysUserMapper;
import com.wut.clock.mongo.dto.FollowParams;
import com.wut.clock.mongo.repository.FollowRepository;
import com.wut.clock.service.IFollowService;
import com.wut.clock.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ZYH
 * @unit D9Lab
 * @description 关注实现类
 * @date 2022/6/11 10:17
 */
@Service
@RequiredArgsConstructor
public class FollowServiceImpl implements IFollowService {

    private final FollowRepository followRepository;

    private final SysUserMapper userMapper;

    private final EventProducer eventProducer;

    @Override
    public int addFollow(FollowParams followParams) {
        // 定义返回
        int res = 0;
        // 获取到当前用户
        Integer userId = ShiroUtil.getUserId();
        SysUser user = userMapper.selectById(userId);
        followParams.setFollowerUserId(userId);
        followParams.setFollowerNickname(user.getNickname());
        followParams.setFollowerAvatar(user.getAvatar());
        followParams.setCreateTime(new Date());
        FollowParams follow = followRepository.findByFollowerUserIdAndFolloweeUserId(userId, followParams.getFolloweeUserId());
        if(follow == null){
            followRepository.save(followParams);
            // 关注事件
            Message message = new Message();
            message.setUserId(userId);
            message.setFromUserId(followParams.getFolloweeUserId());
            message.setType(MessageConstant.Type.FOLLOWER.getCode());
            eventProducer.fireFollowEvent(message);
            res++;
        }
        return res;
    }

    @Override
    public int deleteFollow(Integer followeeUserId) {
        Integer userId = ShiroUtil.getUserId();
        return followRepository.deleteByFollowerUserIdAndFolloweeUserId(userId,followeeUserId);
    }

    @Override
    public Page<FollowParams> getFolloweeList(Integer pageNum, Integer pageSize) {
        Integer userId = ShiroUtil.getUserId();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        return followRepository.findByFollowerUserIdOrderByCreateTimeDesc(userId, pageable);
    }

    @Override
    public Page<FollowParams> getFollowerList(Integer pageNum, Integer pageSize) {
        Integer userId = ShiroUtil.getUserId();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        return followRepository.findByFolloweeUserIdOrderByCreateTimeDesc(userId,pageable);
    }
}
